<?php

namespace july\julyadmin\builder\forms;

use july\julyadmin\builder\FormBase;

/**
 * 高德地图组件
 */
class GaodeMap extends FormBase
{
    /**
     * 添加组件
     * @Author
     * @DateTime 2023-07-16T12:14:26+0800
     * @param    string                   $field 字段
     * @param    string                   $label 名称
     * @return this
     */
    public function __construct($field = '', $label = '')
    {
        $form           = new \stdClass();
        $form->type     = 'gaode-map';
        $form->field    = $field;
        $form->label    = $label;
        $form->help     = '';
        $form->tips     = ['tips' => '', 'direction' => 2, 'time' => 0, 'background' => '#000000'];
        $form->default  = '';
        $form->required = false;

        $config = \july\julyadmin\common\model\Config::config('System');

        if (isset($config['gaode_map_js'])) {
            $this->js = '
            <script type="text/javascript" src="' . $config['gaode_map_js'] . '"></script>
            ';
        }
        $form->gaode_security_key = isset($config['gaode_security_key']) ? $config['gaode_security_key'] : '';

        //内容
        $form->value = '';
        $this->form  = $form;

        $this->css = '
        <link rel="stylesheet" type="text/css" href="/static/assets/admin/js/gaode-map/css/style.css">
        ';

        return $this;
    }

    /**
     * 渲染组件
     * @Author
     * @DateTime 2023-07-16T12:22:46+0800
     * @return   array
     */
    public function render($items_field = '')
    {
        $this->form->value = $this->form->default;

        if (isset($this->data[$this->form->field]) && $this->data[$this->form->field] !== "") {
            $this->form->value = $this->data[$this->form->field];
        }

        //如果坐标为空，默认为天安门国旗位置
        if ($this->form->value) {
            $points = $this->form->value;
        } else {
            $points = "116.399193,39.905081";
        }

        $required_html = $this->form->required && !$this->isView ? ' <font style="color:red;font-weight:bold;font-size:20px;vertical-align:-webkit-baseline-middle;">*</font>' : '';

        //处理tips
        $tips = '';
        if ($this->form->tips['tips']) {
            $tips = '<font class="form-tips-icon"><i class="mdi mdi-information-outline" tips="' . $this->form->tips['tips'] . '" direction="' . $this->form->tips['direction'] . '" time="' . $this->form->tips['time'] . '" background="' . $this->form->tips['background'] . '" onclick="showTips(this)"></i></font>';
        }

        $this->html .= <<< EOT

        <div class="row ps-0 pe-0 ms-0 me-0 mt-3 mb-3 col-md-{$this->colWidth}">
            <label class="col-sm-{$this->labelWidth} col-form-label pe-2 col-form-label-sm text-sm-end text-md-end text-lg-end text-xl-end">
                {$tips}{$this->form->label}
                {$required_html}
            </label>
EOT;
        $input_html = "";
        $disabled   = $this->readonly ? 'disabled' : '';
        if (!$this->isView) {
            $input_html .= '<input type="text" class="form-control gaodemap" id="form-' . $this->form->field . '" name="' . $this->form->field . '"  value="' . $this->form->value . '" ' . ($this->form->required ? ' required' : '') . $this->readonly . ' ' . $disabled . '/>';
        } else {
            $input_html .= '<font class="d-flex align-items-center h-100">';
            $input_html .= $this->form->value !== '' ? $this->form->value : '空';
            $input_html .= '</font>';
        }

        if (!$this->readonly && !$this->isView) {
            $input_html .= <<<EOT

                <div id="form-{$this->form->field}-container" class="gaode-map-container" style="width:100%;height:500px;"></div>
                <div id="form-{$this->form->field}-PageTop" class="gaode-map-PageTop">
                    <table>
                        <tr>
                            <td>
                                <label>请输入关键字：</label>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <input id="form-{$this->form->field}-tipinput" class="gaode-map-tipinput" {$this->readonly} {$disabled}/>
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="error-box"></div>

EOT;
        }

        //处理tips
        $tips = '';
        if ($this->form->tips['tips']) {
            $tips = '<font class="form-tips-icon"><i class="mdi mdi-information-outline" tips="' . $this->form->tips['tips'] . '" direction="' . $this->form->tips['direction'] . '" time="' . $this->form->tips['time'] . '" background="' . $this->form->tips['background'] . '" onclick="showTips(this)"></i></font>';
        }
        $input_html .= $tips;

        //处理help
        if ($this->form->help && !$this->readonly && !$this->isView) {
            $input_html .= <<<EOT

            <div class="form-help form-text">
                <i class="mdi mdi-information-outline"></i>
                <font>{$this->form->help}</font>
            </div>
EOT;
        }

        $this->html .= <<< EOT

            <div class="col-sm-{$this->inputWidth}">
                {$input_html}
            </div>
        </div>
EOT;
        if (!$this->readonly && !$this->isView) {
            $this->script .= <<<EOT
            <script type="text/javascript">
                window._AMapSecurityConfig = {
                    securityJsCode:'{$this->form->gaode_security_key}',
                }
            </script>
            {$this->js}
            <script type="text/javascript">

                //地图加载
                var {$this->form->field}map = new AMap.Map("form-{$this->form->field}-container", {
                    resizeEnable: true
                });

                //输入提示
                var autoOptions = {
                    input: "form-{$this->form->field}-tipinput"
                };

                //标记偏移
                var offset = new AMap.Pixel(-25, -56);


                //标记
                var {$this->form->field}marker = new AMap.Marker({
                    icon:'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                    position:[{$points}],
                    offset: offset
                })
                {$this->form->field}marker.setMap({$this->form->field}map);
                // 将地图视图移动到指定标注位置
                {$this->form->field}map.setCenter({$this->form->field}marker.getPosition());

                //输入框经纬度改变
                $('#form-{$this->form->field}').change(function(){
                    {$this->form->field}map.remove([{$this->form->field}marker]);
                    if($('#form-{$this->form->field}').val()!='' && $('#form-{$this->form->field}').val().indexOf(',')>-1){
                        {$this->form->field}marker = new AMap.Marker({
                            icon:'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                            position:[$('#form-{$this->form->field}').val().split(',')[0],$('#form-{$this->form->field}').val().split(',')[1]],
                            offset: offset
                        });
                        {$this->form->field}marker.setMap({$this->form->field}map);
                        // 将地图视图移动到指定标注位置
                        {$this->form->field}map.setCenter({$this->form->field}marker.getPosition());
                    }
                });



                {$this->form->field}map.on('click', function(e){
                    $('#form-{$this->form->field}').focus();
                    $('#form-{$this->form->field}').val(e.lnglat.lng+','+e.lnglat.lat);
                    {$this->form->field}map.remove([{$this->form->field}marker]);
                    {$this->form->field}marker = new AMap.Marker({
                        icon:'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                        position:[e.lnglat.lng,e.lnglat.lat],
                        offset: offset
                    });
                    {$this->form->field}marker.setMap({$this->form->field}map);
                    setTimeout(function(){
                        $('#form-{$this->form->field}').blur();
                    },100);
                });

                AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete'], function(){
                    var auto = new AMap.AutoComplete(autoOptions);
                    //构造地点查询类
                    var placeSearch = new AMap.PlaceSearch({
                        map: {$this->form->field}map
                    });
                    //注册监听，当选中某条记录时会触发
                    auto.on("select", select);
                    function select(e) {
                        placeSearch.setCity(e.poi.adcode);
                        //关键字查询查询
                        placeSearch.search(e.poi.name);
                        $('#form-{$this->form->field}').focus();
                        $('#form-{$this->form->field}').val(e.poi.location.lng+','+e.poi.location.lat);
                        {$this->form->field}map.remove([{$this->form->field}marker]);
                        {$this->form->field}marker = new AMap.Marker({
                            icon:'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                            position:[e.poi.location.lng,e.poi.location.lat],
                            offset: offset
                        });
                        {$this->form->field}marker.setMap({$this->form->field}map);
                        // {$this->form->field}map.add([{$this->form->field}marker]);
                        setTimeout(function(){
                            $('#form-{$this->form->field}').blur();
                        },100);
                    }
                });
            </script>

EOT;
            $this->js = '';

        }
        $result = ['html' => $this->html, 'script' => $this->script, 'js' => $this->js, 'css' => $this->css];
        return $result;
    }
}
